﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web.Mvc;
using System.Web.Mail;

namespace CoVanHocTapProject.Email
{
    public class EmailMVCTemplateService
    {

        public System.Net.Mail.MailMessage RenderMessage(
                    ControllerContext controllerContext, 
                    string viewName, 
                    object model,
                    string toEmail,
                    string subject)
        {
            string emailBody = "";
            using (var writer = new StringWriter())
            {
                var view = new WebFormView(viewName);
                var vdd = new ViewDataDictionary(model);
                var viewCxt = new ViewContext(controllerContext, view, vdd, new TempDataDictionary(), writer);
                viewCxt.View.Render(viewCxt, writer);
                emailBody = writer.ToString();
            }

            System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
            message.Subject = "Email Subject";
            message.Body = emailBody;
            message.BodyEncoding = Encoding.ASCII;
            message.Subject = subject;
            message.To.Add(toEmail);
            message.IsBodyHtml = true;

            return message;
        }
    }
}
